package com.wngbms.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
public class RedisSupport {

    @Autowired
    RedissonClient redissonClient;

    @Bean
    public ApplicationRunner run1() {
        return args -> {
            RBucket<String> myUser = redissonClient.getBucket("myUser");
            myUser.set("hello miui");
            String s = myUser.get();
            log.info("{}", s);

            ExecutorService executorService = Executors.newFixedThreadPool(20);
            for (int i = 0; i < 20; i++) {
                int index = i;
                executorService.submit(() ->{
//                    RLock fairLock = redissonClient.getFairLock(index % 5 + "");
                    RLock fairLock = redissonClient.getFairLock("12345");
                    fairLock.lock(2000, TimeUnit.MILLISECONDS);
                    try {
                        say();
                    } finally {
                        fairLock.unlock();
                    }
                });
            }
        };
    }

    public static void say() {
        log.info("hello");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
